package mao.redis.protostuffserializer;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import redis.clients.jedis.Jedis;

import java.util.Date;

//protoStuff 序列化与反序列化。
public class ProtostuffSerializer {

    private static Schema<Club> schema = RuntimeSchema.createFrom(Club.class);

    public byte[] serialize(final Club club){
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try{
            return serializeInternal(club,schema,buffer);
        }catch (final Exception e){
            throw new IllegalStateException(e.getMessage(),e);
        }finally {
            buffer.clear();
        }
    }

    private  <T> byte[] serializeInternal(final  T source,final Schema<T> schema,
                                        final LinkedBuffer buffer){
        return ProtostuffIOUtil.toByteArray(source,schema,buffer);
    }

    //result是final合理吗？
    public  <T>  T deserialize(final byte[] bytes, final T result,
                                    final Schema<T> schema){
        ProtostuffIOUtil.mergeFrom(bytes,result,schema);
        return result;
    }

    public static void main(String[] args) {
        ProtostuffSerializer protostuffSerializer = new ProtostuffSerializer();
        Jedis jedis = new Jedis("192.168.255.101",6379);
        String key = "club:1";
        Club club = new Club(1,"AC","米兰",new Date(),1);

        byte[] serialize = protostuffSerializer.serialize(club);
        jedis.set(key.getBytes(),serialize);

        byte[] bytes = jedis.get(key.getBytes());
        Club club1 = protostuffSerializer.deserialize(bytes, schema.newMessage(), schema);
        System.out.println(club1);
    }
}
